{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet"
          href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <!-- Select2 -->
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link href="{% static 'bootstrap-fileinput/css/fileinput.min.css' %}" media="all" rel="stylesheet" type="text/css"/>

    <style>
        /* dataTables列内容居中 */
        #playbook > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #playbook > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        .form-horizontal .form-group {
            margin: 0;
        }

        .form-horizontal .control-label {
            text-align: unset;
            margin-bottom: 5px;
        }

        .form-horizontal .col-sm-6 {
            width: 100%;
        }

        #run-content, #edit-content {
            width: 100%;
            height: 400px;
        }
    </style>
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
{% endblock %}

{% block content %}

    <div class="row">
        <div class="col-sm-7 pull-left" style="margin-bottom: 3px; margin-top: 3px">

            <button class="btn btn-sm btn-success pull-left" data-toggle="modal" style="margin-left: 2px"
                    data-target="#PlaybookEditModal" id="add-playbook">
                <i class="fa fa-edit"></i>
                <span class="bigger-110">在线新增playbook</span>
            </button>

            <button class="btn btn-sm btn-success pull-left" data-toggle="modal" style="margin-left: 2px"
                    data-target="#PlaybookUploadModal">
                <i class="fa fa-upload"></i>
                <span class="bigger-110">上传playbook</span>
            </button>
        </div>
        <div class="col-xs-12">
            <!-- /.box -->
            <div class="box">
                <!-- dataTable -->
                <div class="box-body">
                    <table id="playbook" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th>剧本名称</th>
                            <th>剧本描述</th>
                            <th>添加日期</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for playbook in playbooks %}
                            <tr>
                                <td>{{ playbook.playbook_name }}</td>
                                <td>{{ playbook.playbook_desc|default:"" }}</td>
                                <td>{{ playbook.playbook_time|date:"Y-m-d H:i:s" }}</td>
                                <td>

                                    <button type="button" class="btn btn-success btn-xs modify" data-toggle="modal"
                                            data-target="#PlaybookEditModal" data-id="{{ playbook.id }}">详细/修改
                                    </button>

                                    <button type="button" class="btn btn-primary btn-xs run" data-toggle="modal"
                                            data-target="#PlaybookRunModal" data-id="{{ playbook.id }}">
                                        执行
                                    </button>
                                    <button type="button" class="btn btn-danger btn-xs delete"
                                            data-id="{{ playbook.id }}">
                                        删除
                                    </button>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->

            <div class="box-footer" style="display: none">
                <pre style="background-color: black"></pre>
            </div>

            <!-- PlaybookUploadModal  -->
            <div class="modal fade" id="PlaybookUploadModal" tabindex="-1" role="dialog"
                 aria-labelledby="PlaybookUploadModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title" id="PlaybookUploadModalLabel">
                                上传剧本文件
                            </h4>
                        </div>
                        {% if perms.task.add_ansibleplaybook %}
                            <div class="modal-body">
                                <form id="playbook_detail" class="main form-horizontal">
                                    <fieldset>
                                        <div class="form-group">
                                            <label for="playbook_desc" class="col-sm-2 control-label">剧本描述</label>
                                            <div class="col-sm-6">
                                                <textarea class="form-control" name="playbook_desc" rows="5"
                                                          id="playbook_desc"></textarea>
                                            </div>

                                        </div>

                                        <div class="form-group">
                                            <label for="playbook_file" class="col-sm-2 control-label">剧本文件</label>
                                            <div class="col-sm-6">
                                                <input type="file" id="playbook_file" class="file" name="playbook_file"
                                                       required>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" id="playbook_upload">上传</button>
                            </div>
                        {% else %}
                            <div class="modal-body">
                                抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                            </div>
                        {% endif %}
                    </div><!-- /.modal-content -->
                </div><!-- /.modal -->
            </div>

            <!-- PlaybookEditModal  -->
            <div class="modal fade bd-example-modal-lg" id="PlaybookEditModal" tabindex="-1" role="dialog"
                 aria-labelledby="PlaybookEditModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title" id="PlaybookEditModalLabel">

                            </h4>
                        </div>
                        {% if perms.task.add_ansibleplaybook and perms.task.change_ansibleplaybook %}
                            <div class="modal-body">
                                <form id="playbook_edit" class="main form-horizontal">
                                    <fieldset>
                                        <div class="form-group">
                                            <label for="playbook_name" class="col-sm-2 control-label">剧本名称</label>
                                            <div class="col-sm-6">
                                                <input class="form-control" name="playbook_name" placeholder="必须以.yml结尾"
                                                       id="playbook_name" required>
                                            </div>

                                        </div>

                                        <div class="form-group">
                                            <label for="playbook_desc" class="col-sm-2 control-label">剧本描述</label>
                                            <div class="col-sm-6">
                                                <textarea class="form-control" name="playbook_desc" rows="5"
                                                          id="playbook_desc"></textarea>
                                            </div>

                                        </div>

                                        <div class="form-group">
                                            <label for="edit-content" class="col-sm-2 control-label">剧本内容</label>
                                            <div class="col-sm-6">
                                                <div id="edit-content"></div>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" id="playbook_ops">

                                </button>
                            </div>
                        {% else %}
                            <div class="modal-body">
                                抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                            </div>
                        {% endif %}
                    </div><!-- /.modal-content -->
                </div><!-- /.modal -->
            </div>


            <!-- PlaybookRunModal  -->
            <div class="modal fade bd-example-modal-lg" id="PlaybookRunModal" tabindex="-1" role="dialog"
                 aria-labelledby="PlaybookRunModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title" id="PlaybookRunModalLabel">
                                执行playbook
                            </h4>
                        </div>
                        {% if perms.task.add_ansibleplaybook %}
                            <div class="modal-body">
                                <form id="playbook_info" class="main form-horizontal">
                                    <fieldset>
                                        <div class="form-group">
                                            <label for="inventory"
                                                   class="col-sm-2 control-label">inventory</label>
                                            <div class="col-sm-6">
                                                <select class="form-control select2" multiple="multiple"
                                                        style="width: 100%;" id="inventory" name="inventory">
                                                    {% for ans_group in inventory %}
                                                        <option value="{{ ans_group.id }}">{{ ans_group.ans_group_name }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="run-content" class="col-sm-2 control-label">剧本内容</label>
                                            <div class="col-sm-6">
                                                <div id="run-content"></div>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" data-dismiss="modal" id="playbook_run">
                                    确认执行
                                </button>
                            </div>
                        {% else %}
                            <div class="modal-body">
                                抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                            </div>
                        {% endif %}
                    </div><!-- /.modal-content -->
                </div><!-- /.modal -->
            </div>
        </div>
    </div>
    <!-- /.row -->

{% endblock %}


{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <!-- DataTables -->
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <script src="{% static 'bootstrap-fileinput/js/fileinput.min.js' %}"></script>
    <script src="{% static 'ace/js/ace.js' %}"></script>
    <script src="{% static 'ace/js/mode-yaml.js' %}"></script>
    <script src="{% static 'ace/js/theme-monokai.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'js/jquery-dateFormat.min.js' %}"></script>

    <script>
        $(function () {
            playbook_table = $('#playbook').DataTable({
                columnDefs: [{
                    'targets': [-1,],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });

            // Initialize Select2 Elements
            $('.select2').select2({
                allowClear: true
            });

            $("[data-toggle='tooltip']").tooltip();

            Pace.options.ajax.trackWebSockets = false;

            edit_content = ace.edit("edit-content");
            edit_content.setTheme("ace/theme/monokai");
            let YamlMode = ace.require("ace/mode/yaml").Mode;
            edit_content.session.setMode(new YamlMode());
            edit_content.setShowPrintMargin(false);
        });

        // 初始化fileinput
        $("#playbook_file").fileinput({
            language: 'zh',
            showUpload: false,
            dropZoneEnabled: false,
            msgPlaceholder: '只能上传后缀是.yml的文件',
            allowedFileExtensions: ["yml"],
            showPreview: false,
            showCaption: true,
            maxFileSize: 10240,
            uploadUrl: "{% url 'playbook_upload' %}",
            mergeAjaxCallbacks: true,
            ajaxSettings: {
                headers: {'X-CSRFToken': '{{ csrf_token }}'},
                error: function (response) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: response.msg,
                    })
                },
            },
            browseLabel: '浏览文件',
            removeLabel: '删除',
        }).on('fileuploaded', function (event, data, previewId, index) {
            let playbook_data = {
                playbook_name: data.files[0].name,
                playbook_desc: $('#playbook_desc').val()
            };
            $.ajax({
                url: "{% url 'playbook_upload' %}",
                type: 'POST',
                data: playbook_data,
                dataType: 'json',
                success: function (res) {
                    if (res.code === 200) {
                        let c_time = $.format.date(res.playbook_time, "yyyy-MM-dd HH:mm:ss");
                        playbook_table.row.add([
                            playbook_data.playbook_name,
                            playbook_data.playbook_desc,
                            c_time,
                            `<button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-target="#PlaybookEditModal" data-id="${res.id}"> 详细/修改</button> <button type="button" class="btn btn-primary btn-xs run" data-toggle="modal" data-target="#PlaybookRunModal" data-id="${res.id}"> 执行</button> <button type="button" class="btn btn-danger btn-xs delete" data-id="${res.id}"> 删除</button>`
                        ]).draw();
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: res.msg,
                        })
                    } else {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: res.msg,
                        })
                    }
                },
                error: function (response) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: response.responseText,
                    })
                }
            })
        });

        <!-- playbook操作 -->
        let playbook_tbody = $('#playbook tbody');
        let playbook_ops = $('#playbook_ops');

        // 上传playbook
        $('#playbook_upload').on('click', function () {
            let playbook_file = $("#playbook_file").val();
            if (playbook_file.length === 0) {
                $(this).removeAttr('data-dismiss');
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '请正确选择文件！',
                })
            } else {
                let playbook_name = playbook_file.slice(playbook_file.lastIndexOf('\\') + 1,);
                $.get('/run/check_name/?playbook_name=' + playbook_name, function (res) {
                    if (res.code === 500) {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: res.msg,
                        });
                    } else {
                        $('#playbook_upload').attr('data-dismiss', 'modal');
                        $("#playbook_file").fileinput('upload');
                    }
                })
            }
        });

        // 在线添加playbook
        $('#add-playbook').on('click', function () {
            $("#playbook_edit").trigger('reset');
            $(".select2").val('').trigger('change');
            $('.modal-title').text('新增playbook');
            playbook_ops.text('确认添加');

            // 检查playbook_name的可用性
            $('#playbook_edit #playbook_name').on('blur', function () {
                let playbook_name = $(this).val();
                if (playbook_name.length !== 0) {
                    if (!playbook_name.endsWith('.yml')) {
                        $.confirm({
                            title: 'Tips',
                            content: "文件名必须以.yml结尾",
                            type: 'red',
                            buttons: {
                                OK: function () {
                                    $('#playbook_edit #playbook_name').focus()
                                },
                            }
                        });
                    } else {
                        $.get('/run/check_name/?playbook_name=' + playbook_name, function (res) {
                            if (res.code === 500) {
                                $.confirm({
                                    title: 'Tips',
                                    content: res.msg,
                                    type: 'red',
                                    buttons: {
                                        OK: function () {
                                            $('#playbook_edit #playbook_name').val('')
                                        },
                                    }
                                });
                            } else {
                                // pass
                            }
                        })
                    }
                } else {
                    // pass
                }

            });

            playbook_ops.unbind('click').on('click', function () {
                let playbook_name = $('#playbook_edit #playbook_name').val();
                let playbook_content = edit_content.getSession().getValue();
                if (playbook_name.length === 0 || playbook_content.length === 0) {
                    $(this).removeAttr('data-dismiss');
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请注意必填项！',
                    })
                } else {
                    $(this).attr('data-dismiss', 'modal');
                    let data = {
                        playbook_name: playbook_name,
                        playbook_desc: $('#playbook_edit #playbook_desc').val(),
                        playbook_content: playbook_content,
                    };
                    $.ajax({
                        url: "{% url 'playbook_add' %}",
                        type: 'POST',
                        data: data,
                        dataType: 'json',
                        success: function (res) {
                            if (res.code === 200) {
                                let c_time = $.format.date(res.playbook_time, "yyyy-MM-dd HH:mm:ss");
                                playbook_table.row.add([
                                    data.playbook_name,
                                    data.playbook_desc,
                                    c_time,
                                    `<button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-target="#PlaybookEditModal" data-id="${res.id}"> 详细/修改</button> <button type="button" class="btn btn-primary btn-xs run" data-toggle="modal" data-target="#PlaybookRunModal" data-id="${res.id}"> 执行</button> <button type="button" class="btn btn-danger btn-xs delete" data-id="${res.id}"> 删除</button>`
                                ]).draw();
                                $.alert({
                                    title: 'Tips',
                                    type: 'green',
                                    content: res.msg,
                                })
                            } else {
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: res.msg,
                                })
                            }

                        },
                        error: function (response) {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: response.responseText,
                            })
                        }
                    })
                }
            })
        });

        // 在线修改playbook
        playbook_tbody.on('click', '.modify', function () {
            playbook_ops.attr('data-dismiss', 'modal');
            let playbook_id = $(this).attr('data-id');
            let playbook_td_obj = $(this).parents('tr').children();
            $('.modal-title').text('修改主机组');
            playbook_ops.text('确认修改');
            $.get('/run/playbook_info/' + playbook_id + '/', function (res) {
                $('#playbook_edit #playbook_name').val(res.data.playbook_name);
                $('#playbook_edit #playbook_desc').val(res.data.playbook_desc);
                edit_content.setValue(res.data.playbook_content, -1)
            });

            playbook_ops.unbind('click').on('click', function () {
                let data = {
                    playbook_name: $('#playbook_edit #playbook_name').val(),
                    playbook_desc: $('#playbook_edit #playbook_desc').val(),
                    playbook_content: edit_content.getSession().getValue()
                };
                $.ajax({
                    url: '/run/playbook_info/' + playbook_id + '/',
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function (res) {
                        if (res.code === 200) {
                            playbook_td_obj[0].innerText = data.playbook_name;
                            playbook_td_obj[1].innerText = data.playbook_desc;
                            $.alert({
                                title: 'Tips',
                                type: 'green',
                                content: res.msg,
                            })
                        } else {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: res.msg,
                            })
                        }
                    },
                    error: function (response) {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: response.responseText,
                        })
                    }
                })
            });
        });

        // 执行playbook
        playbook_tbody.on('click', '.run', function () {
            let playbook_id = $(this).attr('data-id');

            $.get('/run/playbook_run/' + playbook_id + '/', function (data) {
                let editor = ace.edit("run-content");
                editor.setTheme("ace/theme/monokai");
                let YamlMode = ace.require("ace/mode/yaml").Mode;
                editor.session.setMode(new YamlMode());
                editor.setShowPrintMargin(false);
                editor.setReadOnly(true);
                editor.setValue(data.content, -1)
            });

            $('#playbook_run').unbind('click').on('click', function () {
                let group_ids = $('#inventory').val();
                if (group_ids.length === 0) {
                    $('#playbook_run').removeAttr('data-dismiss');
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择主机组',
                    })
                } else {
                    $('#playbook_run').attr('data-dismiss', 'modal');
                    let obj = $('pre');
                    let ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
                    let socket = new WebSocket(ws_scheme + '://' + window.location.host + "/ws/ans_playbook_log/");
                    let data = {
                        group_ids: group_ids,
                        playbook_id: playbook_id,
                        run_user: '{{ request.user.id }}',
                        remote_ip: '{{ remote_ip }}'
                    };

                    socket.onopen = function () {
                        $('.box-footer').css('display', 'block');
                        obj.html('开始执行....\n');
                        socket.send(JSON.stringify(data));
                    };

                    socket.onmessage = function (e) {
                        obj.append(e.data)
                    };

                    socket.onclose = function () {
                        obj.append('\n<code>执行完毕....</code>')
                    }
                }
            });
        });

        // 删除playbook
        playbook_tbody.on('click', '.delete', function () {
            {% if perms.task.delete_ansibleplaybook %}
                let pk = $(this).attr('data-id');
                let tr_obj = $(this).parents('tr');
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/run/playbook_del/' + pk + '/',
                                method: 'DELETE',
                                success: function (res) {
                                    if (res.code === 200) {
                                        playbook_table.row(tr_obj).remove().draw();
                                    } else {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: res.msg,
                                        })
                                    }
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除任务的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });
    </script>

{% endblock %}

>